<?php
namespace app\api\controller;

/**
 * 会员中心API
 */

class MemberController extends BaseController {

	/**
	 * 获取会员订阅的分类，type:1为大类、0为小类
	 */
	public function news_cate($uid, $type = 0) {
		$member = db('member')->find($uid);
		if ($type == 0) {
			$cates = db('news_cate')->where('status', 1)->where('id', 'in', $member['yuetype'])->select();
		} else {
			$cates = db('news_cate')->where('status', 1)->where('id', 'in', $member['yuetype1'])->select();
		}
		if ($cates) {
			return $this->toSuccess('获取成功', $cates);
		} else {
			return $this->toError();
		}
	}

	/**
	 * 获取用户model
	 */
	public function index($uid) {
		if (!is_numeric($uid)) {
			return $this->toError('参数错误');
		}
		$member = db('member')->where('status', 1)->find($uid);
		if (!$member) {
			return $this->toError('用户ID不存在');
		}
		$qu = db('district')->find($member['qid']);
		$zhen = db('district')->find($member['zid']);
		$cun = db('district')->find($member['cid']);
		$member['district'] = $qu['name'] . '-' . $zhen['name'] . '-' . $cun['name'];
		return $this->toData($member);
	}

	/**
	 * 修改昵称、性别、登录密码、详细地址、地区
	 */
	public function update($uid, $cate, $content) {
		if (request()->isPost()) {
			if (!is_numeric($uid)) {
				return $this->toError('参数错误');
			}
			switch($cate) {
				case 'password' :
					$password = explode('-', $content);
					$old_pwd = $password[0];
					$data['password'] = md5_salt($password[1]);
					break;
				case 'district' :
					$area = explode('-', $content);
					$data['qid'] = $area[0];
					$data['zid'] = $area[1];
					$data['cid'] = $area[2];
					break;
				default :
					$data[$cate] = $content;
					break;
			}
			$member = db('member')->where('status', 1)->find($uid);
			if (!$member) {
				return $this->toError('用户ID不存在');
			}
			if ($cate == 'password') {
				if ($member['password'] != md5_salt($old_pwd)) {
					return $this->toError('原始密码错误');
				}
			}
			$data['id'] = $uid;
			$data['update_time'] = now_time();
			$result = db('member')->update($data);
			if ($result) {
				return $this->toSuccess('修改成功');
			} else {
				return $this->toError('修改失败');
			}
		} else {
			return $this->toError('请求拒绝');
		}
	}

	/**
	 * 修改头像
	 */
	public function thumb($uid) {
		if (!is_numeric($uid)) {
			return $this->toError('参数错误');
		}
		$json = $this->upload();
		if ($json['code'] == 1) {
			$result = db('member')->where('id', $uid)->setField('thumb', $json['src']);
			if ($result) {
				return $this->toSuccess('修改头像成功', $json['src']);
			} else {
				return $this->toError('修改头像失败');
			}
		} else {
			return $this->toError('头像上传失败');
		}
	}

}
